import 'dart:ui';

import 'package:custom_pop_up_menu/custom_pop_up_menu.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:shimo_app/pages/components/loading_button.dart';

import '../../components/hint.dart';
import 'function_controller.dart';

class FunctionComponent extends StatelessWidget {
  final int containerId;

  FunctionComponent({Key? key, required this.containerId}) : super(key: key);

  final controller = Get.put(FunctionController());
  final state = Get.find<FunctionController>().state;
  final tableHeader = [
    // "操作",
    "任务名称",
    "操作项",
    "参数",
    "单位",
    "操作项",
    "参数",
    "单位",
    "操作项",
    "参数",
    "单位",
  ];
  final TextEditingController _c = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Container(
      // width: 600,
      // height: 1000,
      child: GetBuilder<FunctionController>(builder: (controller) {
        return Stack(
          children: [
            Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        SizedBox(
                          width: 440,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: controller.showTaskSelection
                                ? [
                                    Text("方法名称"),
                                    SizedBox(
                                      width: 20,
                                    ),
                                    SizedBox(
                                      width: 120,
                                      height: 40,
                                      child: DropdownButton(
                                        isExpanded: true,
                                        hint: Text(
                                          "无配置",
                                          style:
                                              TextStyle(color: Colors.black38),
                                        ),
                                        alignment: Alignment.center,
                                        value: controller.selectedTaskIndex,
                                        items: controller.taskList
                                            .map(
                                              (e) => DropdownMenuItem<int>(
                                                value: controller.taskList
                                                    .indexOf(e),
                                                child: Text(e.keys.first),
                                              ),
                                            )
                                            .toList(),
                                        onChanged: (int? value) {
                                          controller.selectedTaskIndex = value!;
                                          controller.selectTask(value);
                                          // _c.text = controller
                                          //     .taskList[value].keys.first;
                                          // // controller.showTaskSelection = false;
                                          // controller.functionName = _c.text;
                                          controller.taskName = controller
                                              .taskList[value].keys.first;
                                          controller.hasEditTaskFunction =
                                              false;
                                          controller.selectedItemIndex = -1;
                                          controller.update();
                                        },
                                      ),
                                    ),
                                    SizedBox(width: 10),
                                    ElevatedButton(
                                      onPressed: () {
                                        if (controller.taskName.isEmpty) {
                                          if (controller.taskList.isNotEmpty) {
                                            controller.taskName = controller
                                                .taskList.first.keys.first;
                                          }
                                        }
                                        controller.showTaskSelection = false;
                                        _c.text = controller.taskName;
                                        controller.newTaskName =
                                            controller.taskName;
                                        controller.addMode = false;
                                        controller.update();
                                      },
                                      child: Text("编辑"),
                                    ),
                                    TextButton(
                                      onPressed: () {
                                        controller.showTaskSelection = false;
                                        controller.newTaskName = "";
                                        _c.text = "";
                                        controller.taskName = "";
                                        controller.addMode = true;
                                        controller.functionList.clear();
                                        controller.displayFunctionList =
                                            controller.generateFunctionItem();
                                        controller.update();
                                      },
                                      child: Text("+新增"),
                                    ),
                                    // TextButton(
                                    //     onPressed: () {
                                    //       controller.showTaskSelection = false;
                                    //       controller.update();
                                    //     },
                                    //     child: Text("返回")),
                                  ]
                                : [
                                    Text(
                                        controller.addMode ? "新增方法" : "当前编辑方法"),
                                    SizedBox(
                                      width: 20,
                                    ),
                                    SizedBox(
                                      width: 120,
                                      height: 40,
                                      child: TextField(
                                        controller: _c,
                                        maxLines: 1,
                                        textAlign: TextAlign.center,
                                        style: const TextStyle(
                                            textBaseline:
                                                TextBaseline.alphabetic),
                                        decoration: InputDecoration(
                                          hintStyle: TextStyle(
                                              color: Color.fromRGBO(
                                                  153, 151, 151, 0.3),
                                              fontSize: 16),
                                          hintText: "输入方法名称",
                                          // border: OutlineInputBorder(),
                                          alignLabelWithHint: true,
                                          contentPadding: EdgeInsets.only(
                                              top: 0, bottom: 0),
                                        ),
                                        onChanged: (value) {
                                          controller.newTaskName = value;
                                          controller.update();
                                        },
                                      ),
                                    ),
                                    SizedBox(
                                      width: 10,
                                    ),
                                    TextButton(
                                      onPressed: () {
                                        controller.showTaskSelection = true;
                                        controller.selectedTaskIndex = 0;
                                        controller.selectTask(0);
                                        controller.update();
                                      },
                                      child: Text("返回"),
                                    ),
                                    ElevatedButton(
                                      onPressed: controller
                                                  .newTaskName.isEmpty ||
                                              controller.newTaskName ==
                                                  controller.taskName
                                          ? null
                                          : () {
                                              controller.addMode
                                                  ? controller.addTask(
                                                      controller.newTaskName,
                                                    )
                                                  : controller.saveTask(
                                                      controller.taskName,
                                                      controller.newTaskName,
                                                    );
                                              controller.showTaskSelection =
                                                  true;
                                              controller.update();
                                            },
                                      child: Text("保存"),
                                    ),
                                    SizedBox(
                                      width: 5,
                                    ),
                                    // ElevatedButton(
                                    //     onPressed: () {
                                    //       controller.showTaskSelection = true;
                                    //       controller.update();
                                    //     },
                                    //     child: Text("载入")),
                                    Visibility(
                                      visible: !controller.addMode,
                                      child: IconButton(
                                        onPressed: controller.taskName.isEmpty
                                            ? null
                                            : () {
                                                controller.removeTask(controller
                                                    .selectedTaskIndex);
                                                controller.taskName = "";
                                                _c.text = controller.taskName;
                                                controller.showTaskSelection =
                                                    true;
                                                controller.functionList.clear();
                                                controller.displayFunctionList =
                                                    controller
                                                        .generateFunctionItem();
                                                controller.update();
                                              },
                                        icon: Icon(
                                          Icons.delete_forever_outlined,
                                          color: Colors.red,
                                        ),
                                      ),
                                    ),
                                  ],
                          ),
                        ),
                        SizedBox(
                          height: 15,
                        ),
                        Row(
                          children: [
                            SizedBox(
                              width: 10,
                            ),
                            SizedBox(
                              width: 100,
                              height: 40,
                              child: DropdownButton(
                                  isExpanded: true,
                                  value: controller.selectedFunction,
                                  items: controller.allFunctions
                                      .map((e) => DropdownMenuItem<int>(
                                            value: controller.allFunctions
                                                .indexOf(e),
                                            child: Text(e.name),
                                          ))
                                      .toList(),
                                  onChanged: (int? value) {
                                    controller.selectedFunction = value!;
                                    controller.showParams();
                                    for (var i in controller.inputControllers) {
                                      i.text = "0";
                                      i.clear();
                                    }
                                    controller.update();
                                  }),
                            ),
                            SizedBox(
                              width: 30,
                            ),
                            ElevatedButton(
                                onPressed: () {
                                  controller.addFunction();
                                },
                                child: Text("添加任务")),
                            SizedBox(
                              width: 30,
                            ),
                            ElevatedButton(
                                onPressed: controller.selectedItemIndex == -1
                                    ? null
                                    : () {
                                        controller.insertFunction(true);
                                      },
                                child: Text("向前插入")),
                            SizedBox(
                              width: 30,
                            ),
                            ElevatedButton(
                                onPressed: controller.selectedItemIndex == -1
                                    ? null
                                    : () {
                                        controller.insertFunction(false);
                                      },
                                child: Text("向后插入")),
                          ],
                        ),
                        SizedBox(
                          height: 20,
                        ),
                        Container(
                          width: 400,
                          height: 300,
                          decoration: BoxDecoration(border: Border.all()),
                          child: Column(
                            children: [
                              Container(
                                  alignment: Alignment.center,
                                  width: 400,
                                  height: 50,
                                  child: Text(
                                    "配置方法参数",
                                    style: TextStyle(color: Colors.white),
                                  ),
                                  color: Colors.black26),
                              Column(
                                children: controller.displayParams.map((e) {
                                  final index =
                                      controller.displayParams.indexOf(e);
                                  return Padding(
                                    padding: const EdgeInsets.only(top: 20),
                                    child: Row(
                                      children: [
                                        SizedBox(
                                          width: 80,
                                        ),
                                        Text(
                                          e.label,
                                          style: TextStyle(
                                              fontSize: 25,
                                              fontWeight: FontWeight.bold),
                                        ),
                                        SizedBox(
                                          width: 10,
                                        ),
                                        SizedBox(
                                          width: 120,
                                          height: 40,
                                          child: e.type == ParamType.select
                                              ? DropdownButton(
                                                  isExpanded: true,
                                                  value: controller
                                                      .paramValues[index],
                                                  alignment:
                                                      AlignmentDirectional
                                                          .center,
                                                  items: e.options
                                                      ?.map((e1) =>
                                                          DropdownMenuItem<int>(
                                                            value: e.options
                                                                ?.indexOf(e1),
                                                            child: Text(e1),
                                                          ))
                                                      .toList(),
                                                  onChanged: (int? value) {
                                                    controller.paramValues[
                                                        index] = value!;
                                                    controller.update();
                                                  })
                                              : e.type == ParamType.integerInput
                                                  ? TextField(
                                                      inputFormatters: [
                                                        // 只允许输入数字
                                                        FilteringTextInputFormatter
                                                            .allow(RegExp(
                                                                r'[0-9]')),
                                                      ],
                                                      onChanged: (val) {
                                                        try {
                                                          controller.paramValues[
                                                                  index] =
                                                              int.tryParse(
                                                                  val)!;
                                                        } catch (e) {
                                                          controller
                                                                  .paramValues[
                                                              index] = 0;
                                                        }
                                                      },
                                                      controller: controller
                                                              .inputControllers[
                                                          index],
                                                      keyboardType:
                                                          TextInputType.number,
                                                      maxLines: 1,
                                                      textAlign:
                                                          TextAlign.center,
                                                      style: TextStyle(
                                                          textBaseline:
                                                              TextBaseline
                                                                  .alphabetic),
                                                      decoration:
                                                          InputDecoration(
                                                        hintStyle: TextStyle(
                                                            color:
                                                                Color.fromRGBO(
                                                                    153,
                                                                    151,
                                                                    151,
                                                                    0.3),
                                                            fontSize: 16),
                                                        hintText: "输入数值",
                                                        // border: OutlineInputBorder(),
                                                        alignLabelWithHint:
                                                            true,
                                                        contentPadding:
                                                            EdgeInsets.only(
                                                                top: 0,
                                                                bottom: 0),
                                                      ),
                                                    )
                                                  : TextField(
                                                      onChanged: (val) {
                                                        double parsedValue =
                                                            double.tryParse(
                                                                    val) ??
                                                                0;
                                                        controller.paramValues[
                                                                index] =
                                                            (parsedValue * 10)
                                                                .toInt();
                                                      },
                                                      controller: controller
                                                              .inputControllers[
                                                          index],
                                                      keyboardType:
                                                          TextInputType.number,
                                                      maxLines: 1,
                                                      textAlign:
                                                          TextAlign.center,
                                                      style: TextStyle(
                                                          textBaseline:
                                                              TextBaseline
                                                                  .alphabetic),
                                                      decoration:
                                                          InputDecoration(
                                                        hintStyle: TextStyle(
                                                            color:
                                                                Color.fromRGBO(
                                                                    153,
                                                                    151,
                                                                    151,
                                                                    0.3),
                                                            fontSize: 16),
                                                        hintText: "输入数值",
                                                        // border: OutlineInputBorder(),
                                                        alignLabelWithHint:
                                                            true,
                                                        contentPadding:
                                                            EdgeInsets.only(
                                                                top: 0,
                                                                bottom: 0),
                                                      ),
                                                    ),
                                        ),
                                        SizedBox(
                                          width: 10,
                                        ),
                                        Text(e.unit)
                                      ],
                                    ),
                                  );
                                }).toList(),
                              )
                            ],
                          ),
                        )
                      ],
                    ),
                    SizedBox(
                      width: 400,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            children: [
                              Text("试剂通道"),
                              Visibility(
                                visible: !controller.isEditingChannelAlias,
                                child: ElevatedButton(
                                    onPressed: () {
                                      controller.isEditingChannelAlias = true;
                                      controller.update();
                                    },
                                    child: Text("编辑")),
                              ),
                              Visibility(
                                visible: controller.isEditingChannelAlias,
                                child: Row(
                                  children: [
                                    ElevatedButton(
                                        onPressed: () {
                                          controller.setChannelAlias();
                                        },
                                        child: Text("确定")),
                                    IconButton(
                                      onPressed: () {
                                        controller.isEditingChannelAlias =
                                            false;
                                        controller.update();
                                      },
                                      icon: Icon(
                                        Icons.cancel,
                                        color: Colors.redAccent,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                          ...List.generate(
                              10,
                              (index) => Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceEvenly,
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    children: [
                                      Text(
                                        "试剂${index + 1}:",
                                        style: TextStyle(
                                            fontWeight: FontWeight.bold),
                                      ),
                                      Container(
                                          alignment: Alignment.center,
                                          width: 200,
                                          height: 40,
                                          child: Row(
                                            children: [
                                              Visibility(
                                                visible: controller
                                                    .isEditingChannelAlias,
                                                child: SizedBox(
                                                  width: 120,
                                                  height: 40,
                                                  child: TextField(
                                                    maxLines: 1,
                                                    textAlign: TextAlign.center,
                                                    style: TextStyle(
                                                        textBaseline:
                                                            TextBaseline
                                                                .alphabetic),
                                                    decoration: InputDecoration(
                                                      hintStyle: TextStyle(
                                                          color: Color.fromRGBO(
                                                              153,
                                                              151,
                                                              151,
                                                              0.3),
                                                          fontSize: 14),
                                                      hintText: "输入试剂名称",
                                                      // border: OutlineInputBorder(),
                                                      alignLabelWithHint: true,
                                                      contentPadding:
                                                          EdgeInsets.only(
                                                              top: 0,
                                                              bottom: 0),
                                                    ),
                                                    onChanged: (val) {
                                                      if (val ==
                                                          controller
                                                                  .inputChannelAlias[
                                                              index]) return;
                                                      controller
                                                              .inputChannelAlias[
                                                          index] = val;
                                                    },
                                                  ),
                                                ),
                                              ),
                                              SizedBox(
                                                width: 6,
                                              ),
                                              Text(
                                                controller.channelAlias[index]
                                                        .isEmpty
                                                    ? "未配置"
                                                    : "(${controller.channelAlias[index]})",
                                                style: TextStyle(
                                                    color: controller
                                                            .channelAlias[index]
                                                            .isEmpty
                                                        ? Colors.grey
                                                        : Colors.black),
                                              ),
                                            ],
                                          )),
                                    ],
                                  )).toList(),
                        ],
                      ),
                    )
                  ],
                ),
                SizedBox(
                  height: 5,
                ),
                Column(
                  children: [
                    Row(
                      children: tableHeader
                          .map((e) => Container(
                                width: 85,
                                child: Text(
                                  e,
                                  style: TextStyle(fontSize: 12),
                                ),
                                decoration: BoxDecoration(border: Border.all()),
                                alignment: Alignment.center,
                              ))
                          .toList(),
                    ),
                    SizedBox(
                      height: 120,
                      child: ListView.separated(
                        itemBuilder: (context, index) {
                          return CustomPopupMenu(
                            menuBuilder: () {
                              final options = ["删除", "选择"];
                              return ClipRRect(
                                borderRadius: BorderRadius.circular(5),
                                child: Container(
                                  width: options.length * 50,
                                  color: const Color(0xFF4C4C4C),
                                  child: Row(
                                    children: options
                                        .map((e) => InkWell(
                                              onTap: () {
                                                if (e == "删除") {
                                                  controller
                                                      .deleteFunction(index);
                                                  showHint(
                                                      "删除成功", HintType.SUCCESS);
                                                }
                                                if (e == "选择") {}
                                                controller.selectedItemIndex =
                                                    index;
                                                controller.update();
                                              },
                                              child: Padding(
                                                padding: const EdgeInsets.only(
                                                    top: 15,
                                                    bottom: 15,
                                                    left: 10,
                                                    right: 10),
                                                child: Text(
                                                  e,
                                                  style: TextStyle(
                                                      color: Colors.white),
                                                ),
                                              ),
                                            ))
                                        .toList(),
                                  ),
                                ),
                              );
                            },
                            pressType: PressType.singleClick,
                            child: Container(
                              color: index == controller.selectedItemIndex
                                  ? Colors.blueAccent
                                  : Colors.transparent,
                              child: Row(
                                children: [
                                  // Container(
                                  //   width: 85,
                                  //   alignment: Alignment.center,
                                  //   child: IconButton(
                                  //       onPressed: () async {
                                  //         if (!await showConfirmDialog("确定删除此任务")) {
                                  //           return;
                                  //         }
                                  //         controller.deleteFunction(index);
                                  //         showHint("删除成功", HintType.SUCCESS);
                                  //       },
                                  //       icon: Icon(Icons.delete)),
                                  // ),
                                  ...controller.displayFunctionList[index]
                                      .map((e) => Container(
                                          width: 85,
                                          alignment: Alignment.center,
                                          child: Text(e)))
                                      .toList(),
                                ],
                              ),
                            ),
                          );
                        },
                        itemCount: controller.displayFunctionList.length,
                        shrinkWrap: true,
                        separatorBuilder: (BuildContext context, int index) {
                          return const Divider(
                              height: 1.0, color: Colors.black12);
                        },
                      ),
                    ),
                    controller.functionList.length > 6
                        ? Icon(Icons.arrow_drop_down)
                        : Text(""),
                  ],
                )
              ],
            ),
            Positioned(
                bottom: 0,
                left: 50,
                child: SizedBox(
                  width: 650,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      ElevatedButton(
                          onPressed: () {
                            controller.refreshData();
                            print(
                                "==${controller.useFunctionLabelList[containerId]}");
                            Navigator.pop(context);
                          },
                          child: Text("取消")),
                      LoadingButton(
                        onPressed: controller.hasEditTaskFunction
                            ? () async {
                                await controller
                                    .saveTaskFunctions(controller.taskName);
                              }
                            : null,
                        child: Row(
                          children: [
                            Icon(Icons.save),
                            Text('保存修改'),
                          ],
                        ),
                      ),
                      ElevatedButton(
                          onPressed: () {
                            controller.useFunctionLabelList[containerId] =
                                List.generate(
                                    controller.displayFunctionList.length,
                                    (i) => controller.displayFunctionList[i]);
                            controller.useFunctionList[containerId] =
                                List.generate(controller.functionList.length,
                                    (i) => controller.functionList[i]);
                            controller.update();
                            controller.deviceService.addOperationLog(
                                containerId, "选择方法:${controller.taskName}");
                            Navigator.pop(context);
                            print(
                                "--labels:${controller.useFunctionLabelList[containerId]}");
                          },
                          child: Text("使用")),
                    ],
                  ),
                ))
          ],
        );
      }),
    );
  }
}
